﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;

using System.Web.UI.WebControls;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.UserControls;


namespace DotNetNuke.Modules.UserDefinedTable
{


  public partial class ExportCSV : PortalModuleBase
  {


    private int ModuleId;

    public ExportCSV()
    {
      //base.Load += new EventHandler(this.Page_Load);
      this.ModuleId = -1;
    }



    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);
      //base.Load += new EventHandler(this.Page_Load);

      cmdCancel.Click += new EventHandler(cmdCancel_Click);
      cmdExport.Click += new EventHandler(cmdExport_Click);
    }




    //protected void Page_Load(object sender, EventArgs evt)
    protected override void OnLoad(EventArgs evt)
    {
      base.OnLoad(evt);

      try
      {
        if (this.Request.QueryString["moduleid"] != null)
          this.ModuleId = int.Parse(this.Request.QueryString["moduleid"]);

        if (!this.Page.IsPostBack)
        {
          IEnumerator enumerator = null;
          this.cboFolders.Items.Insert(0, new ListItem(string.Format("<{0}>", DotNetNuke.Services.Localization.Localization.GetString("None_Specified")), "-"));
          ArrayList list = FileSystemUtils.GetFoldersByUser(this.PortalId, false, false, "READ, WRITE");
          try
          {
            enumerator = list.GetEnumerator();
            while (enumerator.MoveNext())
            {
              FolderInfo current = (FolderInfo)enumerator.Current;
              ListItem item = new ListItem();
              if (current.FolderPath == Null.NullString)
                item.Text = DotNetNuke.Services.Localization.Localization.GetString("Root", this.LocalResourceFile);
              
              else
                item.Text = current.FolderPath;
              
              item.Value = current.FolderPath;
              this.cboFolders.Items.Add(item);
            }
          }
          finally
          {
            if (enumerator is IDisposable)
              (enumerator as IDisposable).Dispose();

          }
          ModuleInfo info = new ModuleController().GetModule(this.ModuleId, this.TabId, false);
          if (info != null)
            this.txtFile.Text = CleanName(info.ModuleTitle);

        }
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);
      }
    }



    private static string CleanName(string Name)
    {
      string str2 = Name;



      foreach (char ch in Path.GetInvalidPathChars())
      {
        str2 = str2.Replace(ch.ToString(), "");
      }
      return str2;
    }




    private void cmdCancel_Click(object sender, EventArgs evt)
    {
      try
      {
        this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);

      }
    }




    private void cmdExport_Click(object sender, EventArgs evt)
    {
      try
      {
        if ((this.cboFolders.SelectedIndex != 0) & (this.txtFile.Text != ""))
        {
          string fileName = CleanName(string.Format("{0}.csv", this.txtFile.Text));
          string message = this.ExportModule(this.ModuleId, fileName, this.cboFolders.SelectedItem.Value, this.rblDelimiter.SelectedValue);
          if (message == "")
          {
            this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
          }
          else
          {
            Skin.AddModuleMessage((PortalModuleBase)this, message, ModuleMessage.ModuleMessageType.RedError);
          }
        }
        else
        {
          Skin.AddModuleMessage((PortalModuleBase)this, DotNetNuke.Services.Localization.Localization.GetString("Validation", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
        }
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);

      }
    }




    private void ExportData(string strFileName, string delimiter)
    {
      DataSet dataSet = new UserDefinedTableController(this.ModuleId, this.TabId, this.UserInfo).GetDataSet(true);
      DataTable data = dataSet.Tables[0];
      DataTable fields = dataSet.Tables[1];
      WriteData(data, fields, strFileName, delimiter);
    }




    private string ExportModule(int ModuleID, string FileName, string Folder, string delimiter)
    {
      string str2 = "";
      ModuleInfo info = new ModuleController().GetModule(ModuleID, this.TabId, false);
      if ((Path.GetExtension(FileName).ToUpper() == ".CSV") && (info != null))
      {
        string strFileName = this.PortalSettings.HomeDirectoryMapPath + Folder + FileName;
        try
        {
          this.ExportData(strFileName, delimiter);
        }
        catch (Exception e)
        {

          Exception exception = e;
          str2 = string.Format("Error occurred: {0}", exception.Message);

        }
      }
      return str2;
    }
    




    private static void WriteData(DataTable Data, DataTable Fields, string fileName, string delimiter)
    {
      using (StreamWriter writer = File.CreateText(fileName))
      {
        IEnumerator enumerator = null;
        IEnumerator enumerator2 = null;
        List<string> list = new List<string>();
        try
        {
          enumerator = Fields.Rows.GetEnumerator();
          while (enumerator.MoveNext())
          {
            DataRow current = (DataRow)enumerator.Current;
            if (DataType.ByName(current[FieldsTableColumn.Type].ToString()).IsUserDefinedField)
              list.Add(current[FieldsTableColumn.Title].ToString());

          }
        }
        finally
        {
          if (enumerator is IDisposable)
            (enumerator as IDisposable).Dispose();

        }
        CSVWriter.WriteCSV(list.ToArray(), writer, delimiter);
        try
        {
          enumerator2 = Data.Rows.GetEnumerator();
          while (enumerator2.MoveNext())
          {
            DataRow row2 = (DataRow)enumerator2.Current;
            List<string> list2 = new List<string>();

            foreach (string str2 in list)
            {
              string str4 = Data.Columns.Contains(str2 + DataTableColumn.Appendix_Original) ? str2 + DataTableColumn.Appendix_Original : str2;
              string item = Utilities.CStrN((row2[str4]), "");
              list2.Add(item);
            }
            CSVWriter.WriteCSV(list2.ToArray(), writer, delimiter);
          }
        }
        finally
        {
          if (enumerator2 is IDisposable)
            (enumerator2 as IDisposable).Dispose();

        }
      }
    }



  }

}

